const testUrl = "https://api-bk.gk8game.com/api/v1/getUserInfo";

// 请求拦截器
const requestInterceptor = (url: string, options: any = {}) => {
  url = testUrl; // TODO
  // 获取 token
  const token = useCookie("token");

  // 设置默认请求头
  const headers = {
    "Content-Type": "application/json",
    ...options.headers,
  };

  // 如果有 token，添加到请求头
  if (token.value) {
    headers.Authorization = `Bearer ${token.value}`;
  }

  // console.log("🚀 请求拦截器:", url, { headers, ...options });

  return {
    ...options,
    headers,
  };
};

// 响应拦截器
const responseInterceptor = (response: any) => {
  // console.log("✅ 响应拦截器 - 成功:", response);
  return response;
};

// 错误拦截器
const errorInterceptor = (error: any) => {
  // console.error("❌ 响应拦截器 - 错误:", error);
  throw error;
};

// 主请求函数
const request = (url: string, options: any = {}) => {
  url = testUrl; // TODO
  return new Promise(async (resolve, reject) => {
    try {
      // 执行请求拦截器
      const interceptedOptions = requestInterceptor(url, options);

      // 发送请求
      const response = await $fetch(url, interceptedOptions);

      // 执行响应拦截器
      const interceptedResponse = responseInterceptor(response);
      resolve(interceptedResponse);
    } catch (error) {
      // 执行错误拦截器
      errorInterceptor(error);
      reject(error);
    }
  });
};
export { request };
